<template>
  <div class="login_container">
      <van-nav-bar
      title="登录页"
    />
    <div class="box">
      <van-form @submit="onSubmit">
      <van-field
        v-model="loginForm.phone"
        name="phone"
        label-width="50px"
        label="手机号"
        placeholder="请输入手机号"
        :rules="loginFormRules.phone"
      />
      <van-field
        v-model="loginForm.password"
        type="password"
        label-width="50px"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="loginFormRules.password"
      />
      <div class="reg"><router-link to="/register">快速注册</router-link></div>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      loginForm: {
        phone: "",
        password: "",
      },
      loginFormRules: {
        //验证用户名是否合法
        username: [
          { required: true, message: "请输入用户名" },
        ],
        // 验证手机号是否合法
        phone: [
          { required: true, message: "请输入手机号码" },
          { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式错误！" },
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: "请输入密码" },
          {
            pattern:/^[0-9]{6,15}$/,message: "密码应在错误！"
          },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      const { data: res } = await this.$http.post("api/login", this.loginForm);
      if (res.status !== 200) return this.$message.fail("登录失败");
      this.$message.success("登录成功");
      window.sessionStorage.setItem("token", res.data.token);
      this.$router.push("/home");
    },
  },
};
</script>

<style lang="less" scoped>
.login_container {
  background-color: #f7f8fa;
  height: 100%;
  max-width: 750px;
}
.reg {
  position: relative;
  left: 260px;
}
.box{
  margin-top: 20px;
}
</style>